<?

/*****************************************************************************

Heartdropper Twitter Server 0.0.3
Copyright (C) 2013 by Jacob Rose

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

*****************************************************************************/

require 'heartdropper.php';
$game = new heartdropper();

/* All inputs are provided on the GET 'service' and 'request' variables */
$service = $_GET['service'];
$request = $_GET['request'];

/* Dispatch request to the appropriate object method */
switch ( $service )
{
	case 'avatar':
		$reply = $game->avatar( $request );
		break;

	case 'reset':
		$reply = $game->reset( $request );
		break;

	case 'poll':
		$reply = $game->poll( $request );
		break;

	case 'fetch':
		$reply = $game->fetch( $request );
		break;

	default:
		/* By default, we provide a welcome message */
                readfile('heartdropper.html');

	
}

/* If we generated a reply, encode it and send it back */
if ( isset( $reply ) && $reply['success'] )
{
	if ( array_key_exists('tweets', $reply ) )
	{
		/* Special format for simplifying message parsing in Unity client */
		foreach ( $reply['tweets'] as $tweet )
		{
			$no_newlines_text = preg_replace('/\s/', ' ', $tweet['text'] );
			$bare_text = preg_replace('/^@heartdropper /', ' ', $no_newlines_text );
			printf(
				"%d,%s,%d,%s,%s\n",
				$tweet['id'], $tweet['username'], $tweet['building'], $tweet['bonus'], $bare_text
			);
		}
	}
	elseif ( array_key_exists('content_type', $reply ) )
	{
		header("Content-type: " . $reply['content_type'] );
		header("Content-length: " . strlen( $reply['content'] ) );
		echo $reply['content'];
	}
}
/* "else" output nothing (if no success) */

?>
